//
//  MKUIElementViewTextField.m
//  MKUI
//
//  Created by 苏尚进 on 2023/7/13.
//  Copyright © 2023 moon. All rights reserved.
//

#import "MKUIElementViewTextField.h"

@interface MKUIElementViewTextField()
@property(nonatomic,strong) UITextField *textField;
@end

@implementation MKUIElementViewTextField
- (id)initWithFrame:(CGRect)frame{
    if(self=[super initWithFrame:frame]){
        self.textField = [[UITextField alloc] init];
        self.textField.font = [UIFont systemFontOfSize:16];
        self.textField.borderStyle = UITextBorderStyleNone;
        self.textField.rightViewMode = UITextFieldViewModeWhileEditing;
        self.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.textField.returnKeyType = UIReturnKeyDone;
        self.textField.textAlignment = NSTextAlignmentRight;
        self.textField.delegate = self;
        [self.textField addTarget:self action:@selector(__onTextValueChange:) forControlEvents:UIControlEventEditingChanged];
        [self.contentView addSubview:self.textField];
        MKUILayoutConstraintItemWrapper *w1 = [MKUILayoutConstraintItemWrapper wrapItem:self.textField sizeThatFitsBlock:^CGSize(MKUILayoutConstraintItemWrapper * _Nonnull wrapper, CGSize size, BOOL resizeItems) {
            return size;
        }];
        self.textFieldLayoutConstraint = w1;
        //
        [self.segLayoutConstraint addItem:w1];
    }
    return self;
}
- (void)setText:(NSString *)text{
    if(_text==text||[_text isEqualToString:text])return;
    _text = text;
    self.textField.text = text;
    [self setNeedsLayout];
}
- (void)__onTextValueChange:(id)sender{
    self.text = self.textField.text;
    if(self.whenChange){
        self.whenChange(self, self.textField.text);
    }
}
#pragma mark - delegate:UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField endEditing:YES];
    if(self.whenReturn){
        self.whenReturn(self);
    }
    return YES;
}
@end

@implementation MKUIElementListViewCellTextField
+ (Class)elementViewClass{
    return MKUIElementViewTextField.class;
}
- (id)initWithFrame:(CGRect)frame{
    if(self=[super initWithFrame:frame]){
        self.enableSelection = NO;
    }
    return self;
}
@end
